package elizaengine;

import java.util.ArrayList;

import elizascript.*;

/**
 * Applies the pre- and post-substitution rules.
 * 
 * @author Caroline
 *
 */
public class SubstitutionRules {
	
	public ScriptInterop script;
	
	public SubstitutionRules (ScriptInterop script) {
		this.script = script;
	}

	// applies presubstitution rules
	public String applyPresubstitutionRule(String input) {
		input = removeSpecialCharacters(input);
		input = applySubstitution(input, script.getPresubstitutionRule(), false);
		return input;
	}

	// applies postsubstitution rules
	public String applyPostsubstitutionRule(String input) {
		return applySubstitution(input, script.getPostsubstitutionRule(), true);
	}
	
	// applies the substitution rules, if the boolean postSubstitution is false, it is
	// assumed that the method is dealing with presubstitiution rules.
	private String applySubstitution(String input, ArrayList<SubstitutionRule> replacementRules, boolean postSubstitution)
	{
		// input is divided into individual parts
		String[] splitInput = input.split(" ");
		input = "";
		// loops through input and checks every segment of the input against every substitution rule
		for (int i = 0; i < splitInput.length; i++) {
			for (int j = 0; j < replacementRules.size(); j++) {
				// Strings matching a substitution ruel are swapped
				if (splitInput[i].equals(replacementRules.get(j).match)) {
					splitInput[i] = replacementRules.get(j).replace;
				}
				// in the case of postsubstitution rules the substitution can take place in both directions
				else if (postSubstitution){
					if(splitInput[i].equals(replacementRules.get(j).replace)){
						splitInput[i] = replacementRules.get(j).match;
					}
				}
			}
			// input is reassembeled
			input += splitInput[i] + " ";
		}
		// excess white space is removed
		String output = input.trim();
		return output;
	}

	// removes all special characters from the String
	// We remove . , & ! ? \ : * and carriage returns's
	private String removeSpecialCharacters(String input) {
		String tempInput = input.replaceAll("[.,&!/?\\[\\]:*\r]", "");
		return tempInput;
	}
}
